import { reactive, toRaw, computed, ref } from "vue";
import { message } from "@/utils/message";
import { HttpPagePar, ConditionalListType } from "@/utils/http/httpPagePar";
import { addApi, deleteApi, enableApi, updataApi } from "@/api/match";
import { getScheduleAndMatchPageDataApi } from "@/api/schedule";
import { getClassTeamApi } from "@/api/team";
import { getTreeApi } from "@/api/classify";
import { getWatchApi } from "@/api/watch";
import { handleTree } from "@/utils/tree";
import {
  scheduleStarttimeVf,
  classifyVf,
  starttimehourVf,
  watchidVf,
  teamaidVf,
  teambidVf,
  teamascoreVf,
  teambscoreVf
} from "@/common/validator";
import { matchDto } from "@/Model/match";
import { CmpHandleStateEnum, CmpGlobal } from "@/common/GlobalType";
import { CustomMouseMenu } from "@howdyjs/mouse-menu";
import { dateTimeToString } from "@/utils/datetime";
import type { FormRules, FormInstance } from "element-plus";
import type { PaginationProps } from "@pureadmin/table";

interface CmpGlobalType extends CmpGlobal {
  classifyTreeData: any[];
  teamSelectData: any[];
  watchSelectData: any[];
}
type SearchFormType = {
  starttime: any;
  ifdisable: string;
  remark: string;
  classid: number;
  classifytree: any[];
};

/**
 * 观看平台hook
 * @returns columns 表格头部列 {obiect} onSearch 表格搜索事件 {obiect}
 */
export function useWatch() {
  const tableRef = ref();

  const ruleFormRef = ref<FormInstance>();
  /** 分类树形选择框ref */
  const tree = ref(null);
  /** 搜索区树形选择框ref */
  const searchtree = ref(null);
  /** 表格头部列 */
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      minWidth: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "比赛日期",
      prop: "schedule.starttimeStr"
    },
    {
      label: "所属分类",
      prop: "classify.name"
    },
    {
      label: "比赛时间",
      prop: "starttimeHour",
      cellRenderer: ({ row }) =>
        row.datatype === "match" ? row.starttimeHour : ""
    },
    {
      label: "队伍一",
      prop: "teama.name",
      cellRenderer: ({ row }) =>
        row.datatype === "match" ? row.teama.name : ""
    },
    {
      label: "队伍一比分",
      prop: "teamascore",
      cellRenderer: ({ row }) =>
        row.datatype === "match" ? row.teamascore : ""
    },
    {
      label: "队伍二",
      prop: "teamb.name",
      cellRenderer: ({ row }) =>
        row.datatype === "match" ? row.teamb.name : ""
    },
    {
      label: "队伍二比分",
      prop: "teambscore",
      cellRenderer: ({ row }) =>
        row.datatype === "match" ? row.teambscore : ""
    },
    {
      label: "是否禁用",
      prop: "ifdisable",
      cellRenderer: ({ row, props }) =>
        row.datatype === "match" ? (
          <el-tag
            size={props.size}
            type={row.ifdisable === 1 ? "success" : "danger"}
            effect="plain"
          >
            {row.ifdisable === 1 ? "启用" : "禁用"}
          </el-tag>
        ) : (
          ""
        )
    },
    {
      label: "操作",
      slot: "operation"
    }
  ];
  /** 组件需要全局使用的变量 */
  const cmpglobal = reactive<CmpGlobalType>({
    dialogVisible: false,
    cmpHandleState: CmpHandleStateEnum.View,
    ids: [],
    tableTitle: "比赛列表-添加比赛请在相应的赛程上点击右键进行添加",
    classifyTreeData: [],
    teamSelectData: [],
    watchSelectData: []
  });
  /** 更新或添加表单 */
  const addorupdataform = reactive<matchDto>({
    id: 0,
    ifdisable: 1,
    classid: 0,
    classifytree: [],
    scheduleid: 0,
    schedulename: "",
    schedulestarttime: "",
    starttime: "",
    starttimehour: "",
    teamaid: 0,
    teambid: 0,
    teamascore: 0,
    teambscore: 0,
    watchid: 0,
    remark: ""
  });
  /** 表单验证对象 */
  const rules = reactive<FormRules>({
    schedulename: scheduleStarttimeVf,
    classifytree: classifyVf,
    starttimehour: starttimehourVf,
    watchid: watchidVf,
    teamaid: teamaidVf,
    teambid: teambidVf,
    teamascore: teamascoreVf,
    teambscore: teambscoreVf
  });
  /** 搜索框表单 */
  const searchform = reactive<SearchFormType>({
    starttime: "",
    ifdisable: "1",
    remark: "",
    classid: 0,
    classifytree: []
  });
  /** 表格绑定数据对象 */
  const tabledata: any = reactive({
    data: []
  });
  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    total: 0,
    align: "center",
    background: true,
    small: false
  });
  /** dialog标题 */
  const dialogtitle = computed(() => {
    let res = "";
    switch (cmpglobal.cmpHandleState) {
      case CmpHandleStateEnum.Add:
        res = "新增";
        break;
      case CmpHandleStateEnum.Updata:
        res = "修改";
        break;
      default:
        res = "查看";
        break;
    }
    return res;
  });
  /** 表单输入框是否禁用 */
  const ifDisabledForm = computed(() => {
    if (cmpglobal.cmpHandleState === CmpHandleStateEnum.View) {
      return true;
    } else {
      return false;
    }
  });
  /** 表单输入框是否禁用 */
  const ifDisabledFormResetBut = computed(() => {
    if (cmpglobal.cmpHandleState === CmpHandleStateEnum.Add) {
      return false;
    } else {
      return true;
    }
  });

  /** api数据请求体 */
  const httpPagePar = new HttpPagePar();
  /**
   * 向服务器请求表格数据
   */
  function getPageData() {
    httpPagePar.pageNum = pagination.currentPage;
    httpPagePar.pageSize = pagination.pageSize;
    const conditionallist: ConditionalListType[] = [];
    if (searchform.starttime.length === 2) {
      const startdate: ConditionalListType = {
        key: 0,
        value: {
          fieldName: "starttime",
          fieldValue: dateTimeToString(searchform.starttime[0]),
          cSharpTypeName: "DateTime",
          conditionalType: 3
        }
      };
      conditionallist.push(startdate);
      const stopdate: ConditionalListType = {
        key: 0,
        value: {
          fieldName: "starttime",
          fieldValue: dateTimeToString(searchform.starttime[1]),
          cSharpTypeName: "DateTime",
          conditionalType: 5
        }
      };
      conditionallist.push(stopdate);
    }
    if (searchform.remark !== "") {
      const item: ConditionalListType = {
        key: 0,
        value: {
          fieldName: "remark",
          fieldValue: searchform.remark,
          cSharpTypeName: "string",
          conditionalType: 1
        }
      };
      conditionallist.push(item);
    }
    if (searchform.ifdisable === "0" || searchform.ifdisable === "1") {
      const item: ConditionalListType = {
        key: 0,
        value: {
          fieldName: "ifdisable",
          fieldValue: searchform.ifdisable,
          cSharpTypeName: "long",
          conditionalType: 0
        }
      };
      conditionallist.push(item);
    }
    if (searchform.classid !== 0) {
      const item: ConditionalListType = {
        key: 0,
        value: {
          fieldName: "classid",
          fieldValue: String(searchform.classid),
          cSharpTypeName: "long",
          conditionalType: 0
        }
      };
      conditionallist.push(item);
    }
    if (conditionallist.length > 0) {
      httpPagePar.conditionalList = conditionallist;
    } else {
      httpPagePar.conditionalList = [];
    }
    httpPagePar.orderBys = ["starttime desc"];

    getScheduleAndMatchPageDataApi(httpPagePar)
      .then(res => {
        if (res.code === 1) {
          tabledata.data = res.data.data;
          pagination.total = res.data.total;
        } else {
          message(res.msg, { type: "error" });
          tabledata.data = [];
          pagination.total = 0;
        }
      })
      .catch(err => {
        message(`获取表格数据失败:${err}`, { type: "error" });
        console.log(err);
      });
  }

  /**
   * 搜索事件
   */
  const clickSearch = () => {
    pagination.currentPage = 1;
    getPageData();
  };
  /**
   * 分页控件选择显示多少条数据事件
   */
  function onSizeChange(val) {
    pagination.pageSize = val;
    //重新获取数据
    getPageData();
  }
  /**
   * 分页控件选择页码事件
   */
  function onCurrentChange(val) {
    pagination.currentPage = val;
    //重新获取数据
    getPageData();
  }

  /**
   * 表格的刷新事件
   */
  function onSearch() {
    //重新获取数据
    getPageData();
  }
  /**
   * 表格查看事件
   * @param row 选中数据
   */
  function handleView(row) {
    cmpglobal.cmpHandleState = CmpHandleStateEnum.View;
    cmpglobal.dialogVisible = true;
    SetFormData(row);
  }

  /**
   * 表格修改事件
   * @param row 选中数据
   */
  function handleUpdate(row) {
    cmpglobal.cmpHandleState = CmpHandleStateEnum.Updata;
    cmpglobal.dialogVisible = true;
    SetFormData(row);
  }
  /**
   * 网络请求禁用数据
   * @param params id数组
   */
  function Delete(params: number[]) {
    deleteApi({ ids: params })
      .then(res => {
        if (res.code === 1) {
          message(res.msg, { type: "success" });
          //更新数据
          getPageData();
        } else {
          message(res.msg, { type: "error" });
        }
        cmpglobal.ids = [];
      })
      .catch(err => {
        cmpglobal.ids = [];
        message(`禁用失败:${err}`, { type: "error" });
        console.log(err);
      });
  }
  /**
   * 网络请求禁用数据
   * @param params id数组
   */
  function Enable(params: number[]) {
    enableApi({ ids: params })
      .then(res => {
        if (res.code === 1) {
          message(res.msg, { type: "success" });
          //更新数据
          getPageData();
        } else {
          message(res.msg, { type: "error" });
        }
        cmpglobal.ids = [];
      })
      .catch(err => {
        cmpglobal.ids = [];
        message(`禁用失败:${err}`, { type: "error" });
        console.log(err);
      });
  }
  /**
   * 表格删除事件
   * @param row 选中数据
   */
  function handleDelete(row) {
    Delete([row.id]);
  }
  /**
   * 表格启用事件
   * @param row 选中数据
   */
  function handleEnable(row) {
    Enable([row.id]);
  }
  /**
   * 批量删除
   */
  function handleBatchDelete() {
    if (cmpglobal.ids.length <= 0) {
      message("请选择需要禁用的数据", { type: "error" });
    } else {
      Delete(toRaw(cmpglobal.ids));
    }
  }
  /**
   * 批量启用
   */
  function handleBatchEnable() {
    if (cmpglobal.ids.length <= 0) {
      message("请选择需要禁用的数据", { type: "error" });
    } else {
      Enable(toRaw(cmpglobal.ids));
    }
  }
  /**
   * 表格选择列的事件
   * @param val 选中数据
   */
  function handleSelectionChange(val) {
    if (val.length > 0) {
      let selectids: number[] = [];
      let ifbl = false;
      val.forEach(function (item) {
        if (item.datatype === "schedule") {
          ifbl = true;
          return;
        }
        selectids.push(item.id);
      });
      if (ifbl) {
        message("不能选择赛程数据,请重新选择", { type: "error" });
        clearSelection();
        selectids = [];
      }
      cmpglobal.ids = selectids;
    }
  }

  /**
   * 重置搜索表单
   */
  function resetSearchForm() {
    searchform.starttime = "";
    searchform.remark = "";
    searchform.ifdisable = "";
    searchform.classid = 0;
    searchform.classifytree = [];
    //searchtree.value.setCheckedKeys([]);
    getPageData();
  }
  /**
   * 重置表单
   */
  function resetAddOrUpdataForm() {
    addorupdataform.id = 0;
    //addorupdataform.watchid = null;
    addorupdataform.teamaid = null;
    addorupdataform.teambid = null;
    addorupdataform.teamascore = 0;
    addorupdataform.teambscore = 0;
    addorupdataform.starttimehour = null;
    addorupdataform.ifdisable = 1;
    addorupdataform.starttime = "";
    addorupdataform.remark = "";
  }
  /**
   * 设置表单数据
   * @param row 行数据
   */
  function SetFormData(row: any) {
    getClassTeam(row.classid);
    getWatch();
    addorupdataform.id = row.id;
    addorupdataform.classid = row.classid;
    addorupdataform.classifytree = row.classid;
    addorupdataform.scheduleid = row.scheduleid;
    addorupdataform.schedulename = row.schedule.starttimeStr;
    addorupdataform.schedulestarttime = row.schedule.starttime; //赛程时间
    addorupdataform.watchid = row.watchid;
    addorupdataform.teamaid = row.teamaid;
    addorupdataform.teambid = row.teambid;
    addorupdataform.teamascore = row.teamascore;
    addorupdataform.teambscore = row.teambscore;
    addorupdataform.starttimehour = row.starttime; //表单比赛时间
    addorupdataform.ifdisable = row.ifdisable;
    addorupdataform.starttime = row.starttime;
    addorupdataform.remark = row.remark;
  }
  /**
   * 点击添加事件
   */
  function addClick(row: any) {
    getClassTeam(row.classid);
    getWatch();
    addorupdataform.classid = row.classid;
    addorupdataform.classifytree = row.classid;
    addorupdataform.scheduleid = row.scheduleid;
    addorupdataform.schedulename = row.schedule.starttimeStr;
    addorupdataform.schedulestarttime = row.schedule.starttime; //赛程时间
    addorupdataform.watchid = row.classify.watchid;
    cmpglobal.dialogVisible = true;
    cmpglobal.cmpHandleState = CmpHandleStateEnum.Add;
    resetAddOrUpdataForm();
  }
  /**
   * 保存按键事件
   */
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, _fields) => {
      if (valid) {
        if (cmpglobal.cmpHandleState === CmpHandleStateEnum.Add) {
          //新增 2023-03-20 20:43:24
          //赛程时间
          addorupdataform.starttime = getScheWatchTime(
            addorupdataform.schedulestarttime,
            addorupdataform.starttimehour
          );
          addApi(toRaw(addorupdataform))
            .then(res => {
              if (res.code === 1) {
                message(res.msg, { type: "success" });
                //重置表单
                resetAddOrUpdataForm();
                //更新数据
                getPageData();
              } else {
                message(res.msg, { type: "error" });
              }
            })
            .catch(err => {
              message("添加失败:" + err, { type: "error" });
            });
        }
        if (cmpglobal.cmpHandleState === CmpHandleStateEnum.Updata) {
          //更新
          //赛程时间
          addorupdataform.starttime = getScheWatchTime(
            addorupdataform.schedulestarttime,
            addorupdataform.starttimehour
          );

          updataApi(toRaw(addorupdataform))
            .then(res => {
              if (res.code === 1) {
                message(res.msg, { type: "success" });
                //重置表单
                resetAddOrUpdataForm();
                //更新数据
                getPageData();
                cmpglobal.dialogVisible = false;
              } else {
                message(res.msg, { type: "error" });
              }
            })
            .catch(err => {
              message("更新失败:" + err, { type: "error" });
              //重置表单
              resetAddOrUpdataForm();
              cmpglobal.dialogVisible = false;
            });
        }
      } else {
        // console.log("表单验证失败", fields);
        message("请输入必填项", { type: "error" });
      }
    });
  };
  /**
   * 用赛程日期加比赛时间拼接比赛日期时间
   */
  function getScheWatchTime(
    schedulestarttime: string,
    starttimehour: string
  ): string {
    const rq = schedulestarttime.substring(0, 10);
    //表单比赛时间
    let sj = "";
    if (typeof starttimehour === "object") {
      sj = dateTimeToString(starttimehour).substring(11, 16);
    } else {
      sj = starttimehour.substring(11, 16);
    }
    return rq + " " + sj + ":00";
  }

  /**
   * dialog对话框关闭回调函数
   */
  function dialogClose() {}
  /**
   * dialog对话框打开回调函数
   */
  function dialogOpen() {
    //获取所有分类的树形数据
    //getClassifyTreeData();
  }
  /**
   * 获取所有分类的树形数据
   */
  function getClassifyTreeData() {
    getTreeApi()
      .then(res => {
        cmpglobal.classifyTreeData = [];
        if (res.code === 1) {
          cmpglobal.classifyTreeData = handleTree(res.data);
        } else {
          message(res.msg, { type: "error" });
          console.log(res);
        }
      })
      .catch(err => {
        message("获取分类失败:" + err, { type: "error" });
        console.log(err);
      });
  }
  /**
   * 分类树形选择框选中事件 用来解决默认不能单选的问题
   */
  function classifyTreeCheckChange(item, checked, _self) {
    if (checked) {
      addorupdataform.classid = item.id;
      tree.value.setCheckedKeys([item.id]);
    } else {
      if (addorupdataform.classid === item.id) {
        tree.value.setCheckedKeys([item.id]);
      }
    }
  }
  /**
   * 搜索栏分类树形选择框选中事件 用来解决默认不能单选的问题
   */
  function searchClassifyTreeCheckChange(item, checked, _self) {
    if (checked) {
      searchform.classid = item.id;
      searchtree.value.setCheckedKeys([item.id]);
    } else {
      if (searchform.classid === item.id) {
        searchtree.value.setCheckedKeys([item.id]);
      }
    }
  }
  /**
   * 数据表格右键菜单
   */
  const menuOptions = {
    menuList: [
      {
        label: "添加比赛数据",
        fn: row => addClick(row)
      }
    ]
  };
  /**
   * 数据表格右键菜单
   */
  function showMouseMenu(row, column, event) {
    event.preventDefault();
    const { x, y } = event;
    const ctx = CustomMouseMenu({
      el: event.currentTarget,
      params: row,
      // 菜单容器的CSS设置
      menuWrapperCss: {
        background: "var(--el-bg-color)"
      },
      menuItemCss: {
        labelColor: "var(--el-text-color)",
        hoverLabelColor: "var(--el-color-primary)",
        hoverTipsColor: "var(--el-color-primary)"
      },
      ...menuOptions
    });
    ctx.show(x, y);
  }
  /**
   * 获取特定分类的队伍api
   */
  function getClassTeam(classid: any) {
    getClassTeamApi(classid)
      .then(res => {
        if (res.code === 1) {
          cmpglobal.teamSelectData = res.data;
        } else {
          message(res.msg, { type: "error" });
          console.log(res);
        }
      })
      .catch(err => {
        message("获取队伍数据失败:" + err, { type: "error" });
        console.log(err);
      });
  }
  /**
   * 获取所有未禁用的观看平台api
   */
  function getWatch() {
    getWatchApi()
      .then(res => {
        if (res.code === 1) {
          cmpglobal.watchSelectData = res.data;
        } else {
          message(res.msg, { type: "error" });
          console.log(res);
        }
      })
      .catch(err => {
        message("获取观看平台数据失败:" + err, { type: "error" });
        console.log(err);
      });
  }
  /**
   * 清空表格选择的数据
   */
  function clearSelection() {
    tableRef.value.getTableRef().clearSelection();
  }
  return {
    columns,
    onSearch,
    searchform,
    tabledata,
    getPageData,
    handleView,
    handleUpdate,
    handleDelete,
    handleSelectionChange,
    handleBatchDelete,
    handleBatchEnable,
    cmpglobal,
    dialogtitle,
    addorupdataform,
    resetSearchForm,
    resetAddOrUpdataForm,
    rules,
    submitForm,
    pagination,
    onSizeChange,
    onCurrentChange,
    clickSearch,
    dialogClose,
    handleEnable,
    ifDisabledForm,
    ifDisabledFormResetBut,
    dialogOpen,
    tree,
    classifyTreeCheckChange,
    getClassifyTreeData,
    searchClassifyTreeCheckChange,
    searchtree,
    showMouseMenu,
    tableRef,
    ruleFormRef
  };
}
